//
//  PhotoViewController.swift
//  个人微博
//
//  Created by guo3920591 on 16/4/28.
//  Copyright © 2016年 guo3920591. All rights reserved.
//

import UIKit
import SDWebImage
/// 单张照片选择控制器
class PhotoViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        loadImag()
    }
    
// MARK: - 私有控件
    
    private lazy var  scroller: UIScrollView = UIScrollView()
    
    private lazy var  photoImg: UIImageView = UIImageView()
    
    private let urlString: String
    
     let  photoIndex: Int
    
    init(urlString: String,photoIndex: Int){
        
        self.urlString = urlString
        
        self.photoIndex = photoIndex
        
        super.init(nibName: nil, bundle: nil)
        
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
// MARK: - 加载图像
    
    private  func loadImag(){
      
        guard let url = NSURL(string: urlString) else{
            return
        }
        
    photoImg.sd_setImageWithURL(url, placeholderImage: nil) { (image, _, _, _) -> Void in
        guard let image = image else {
            
            return
        }
        
        
        self.setImagePosition(image)
        
        }
    
    }
    
    
    private func setImagePosition(image: UIImage){
        
        let size = imageSizeWithScreen(image)
        
        photoImg.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        
        scroller.contentSize = size
        
        //短图
        
        if size.height <= scroller.bounds.height {
            
            photoImg.center = scroller.center
            
        }
        
        
    }
    
    
    private func imageSizeWithScreen(image: UIImage) -> CGSize{
        
        var size = UIScreen.mainScreen().bounds.size
        
        size.height = image.size.height * size.width / image.size.width
        
        return size
        
        
    }
    
}

// MARK: - 布局界面
extension PhotoViewController{
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.blackColor()
        
        view.addSubview(scroller)
        
        scroller.frame = view.bounds
        
        scroller.addSubview(photoImg)
    }
    
    
}